__author__ = 'alex'
# -*- coding: utf-8 -*-

from dictclient import  *
from difflib import get_close_matches
import re

# this cut level is enough to match 3 letter word + 2 addition letters
# or replace 1 letter in 4 letter word
cut = 0.75

def refine(word):
    return word.strip().lower()

def splitAttrib(word):
    return word.lower().replace('_', ' ').split()

def normalize(string):
    return ("_".join(string.split())).lower()

class Translator(object):
    def __init__(self, dbname = "mueller7"):
        self.conn = Connection()
        self.dbname = dbname
        self.regex = re.compile(u"\s([А-Яа-яЁё -]+)([\s?!;,.]|$)", re.UNICODE | re.MULTILINE)

    def getDefinitions(self, word):

        response = self.conn.define(self.dbname, refine(word).encode("utf-8"))

        s = u''
        for block in response:
            s += unicode(block.getdefstr(), "utf-8")

        return [ d[0] for d in self.regex.findall(s) ]


class Attribute(object):

    def __init__(self, str, translator):

        words = splitAttrib(str)
        self.sourceString = normalize(str)
        self.translations = [ (word, translator.getDefinitions(word)) for word in words ]

    #return True if str is a translation of this attribute
    def isTranslation(self, str, direct_match = False):

        #straight match(in English) without translation
        if normalize(str) == self.sourceString:
            return True

        #empyness test
        words = splitAttrib(str)
        if len(words) == 0 or len(self.translations) == 0:
            return False

        #check each world to be one of this attribute words translations
        for word in words:
            matches = 0
            for translation in self.translations:

                #test if translation have absolutely the same word
                if direct_match:
                    if word in translation[1]:
                        matches += 1

                #test if translation have similar word
                else:
                    #return 1 closest word(in list)
                    close_word = get_close_matches(word, translation[1], n  = 1, cutoff = cut)
                    matches += len(close_word)

            if matches == 0:
                #didn`t find translation for word
                return False
        return True


'''

t = Translator()

phrase = u"Birth_date"

a = Attribute(phrase, t)

for w in a.translations:
    print w[0], ":  ",
    for definition in w[1]:
        print definition, ",",
    print ""


word = u"даТа__рождения"

print a.isTranslation(word)

'''